// interface EPaySDKConfig {
//   appId: string
//   secretKey: string
//   gatewayUrl?: string
//   signType?: 'MD5'
// }

const { log } = require('console');
const  crypto =require('crypto') 
const  axios =require('axios') 

class EPaySDK {;

  constructor(config) {
    this.config = {
      gatewayUrl: 'https://pay.tianmuzf.top',
      signType: 'MD5',
      ...config
    };
  }

  async pageExecute(resFormat, params) {
    const { appId, secretKey, gatewayUrl, signType } = this.config
    const {
      bizContent:{
        type,
        out_trade_no,
        name,
        money,
        sitename='',
      },
      return_url,
      notify_url,
    } = params
    const obj = {
      type:1,
      out_trade_no,
      name:'dddd',
      return_url,
      notify_url,
      sitename,
      money,
      pid: appId,
    }
    const queryStr = this.toQueryString(this.objKeySort(obj))
    let sign = ''
    if (signType === 'MD5') {
      sign = crypto
        .createHash('md5')
        .update(queryStr + secretKey)
        .digest('hex')
    }
    const url = `${gatewayUrl}/mapi.php?${queryStr}&sign=${sign}&sign_type=${signType}`
    const hrefRes = await axios.get(url)
    console.log(hrefRes,55,obj,url)
  }

  /**
   * 对象key值排序
   * @param {object} obj 待排序对象
   * @param {boolean} asc 是否升序 默认升序
   * @returns newObj
   */
   objKeySort(obj, asc=true) {
    const newKey = Object.keys(obj).sort(
      asc ? (a, b) => a.localeCompare(b) : (a, b) => b.localeCompare(a),
    )
    const newObj = {} 
    for (const i of newKey) {
      newObj[i] = obj[i]
    }
    return newObj
  }


 /**
   * 将对象拼接为查询字符串(过滤掉sign和sign_type、排除空值)
   * @param {object} obj
   * @returns queryString
   */
  toQueryString(obj) {
    const queryString = Object.entries(obj)
      .filter(([key, value]) => !['sign', 'sign_type'].includes(key) && value !== '')
      .map(([key, value]) => `${key}=${value}`)
      .join('&')
    return queryString
  }
}


const ePaySDK = new EPaySDK({
  appId: process.env.EZF_APPID ,
  secretKey: process.env.EZF_SECRET_KEY,
})

module.exports = {
    ePaySDK
}